package com.marvels.financial.loan.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.marvels.common.constants.PayContants;
import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dao.McfePaymentWithholdDao;
import com.marvels.financial.loan.dao.McfePaymentWithholdDetailDao;
import com.marvels.financial.loan.dao.McfeRepaymentFlowDao;
import com.marvels.financial.loan.dto.McfeCustomerLoanContractDTO;
import com.marvels.financial.loan.dto.McfePaymentWithholdDTO;
import com.marvels.financial.loan.dto.McfePaymentWithholdDetailDTO;
import com.marvels.financial.loan.dto.PaymentResponse;
import com.marvels.financial.loan.dto.WithholeQueryConditionDTO;
import com.marvels.financial.loan.service.WithholdPaymentApi;
import com.marvels.financial.loan.service.WithholdResultQueryTaskletApi;

import net.sf.json.JSONObject;

@Service
public class WithholdResultQueryTaskletImpl implements WithholdResultQueryTaskletApi {

	@Autowired
	private McfePaymentWithholdDetailDao detailDao;

	@Autowired
	private WithholdPaymentApi withholdPaymentApi;

	@Autowired
	private McfeCustomerLoanContractDao contractDao;

	@Autowired
	private McfeRepaymentFlowDao flowDao;

	@Autowired
	private McfePaymentWithholdDao withholdDao;


	@Override
	public void withholdResultQuery() {
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>定时代扣还款计划结果查询开始");
		if (!"on".equalsIgnoreCase(CommonProperties.getTimingWithholdQuery())) {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>定时代扣还款计划结果查询开关关闭");
			return;
		}

		String batchName = Thread.currentThread().getId() + "-" + UUID.randomUUID().toString().replace("-", "");
		// 先将交易结果处于处理中的代扣流水详情占用
		int count = detailDao.updateBatchName(batchName);
		if (count < 1) {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>没有处于代扣中的代扣流水信息");
			return;
		}
		// 查询出被该批次号占用的代扣流水详情
		List<McfePaymentWithholdDetailDTO> listDTO = detailDao.selectByBatchName(batchName);
		for (McfePaymentWithholdDetailDTO detailDTO : listDTO) {
			String loanId = detailDTO.getLoanId();
			// 查询合同状态
			McfeCustomerLoanContractDTO contractDTO = contractDao.selectContractByLoanId(loanId);
			if (contractDTO.getStatus()!=0 && contractDTO.getStatus()!=1) {
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>loanId:" + loanId + "查询代扣状态时,合同状态不处于还款中");
				McfePaymentWithholdDetailDTO detailDTOUpdate = new McfePaymentWithholdDetailDTO();
				detailDTOUpdate.setId(detailDTO.getId());
				detailDTOUpdate.setUpdatedBy("SYSTEM");
				detailDTOUpdate.setUpdatedDate(new Date());
				detailDTOUpdate.setBatchStatus("2");// 将批次状态改成处理完成
				detailDao.updateByPrimaryKeySelective(detailDTOUpdate);
				continue;
			}
			PaymentResponse paymentResponse = null;
			WithholeQueryConditionDTO conditionDTO = new WithholeQueryConditionDTO();
			conditionDTO.setFundSource(detailDTO.getFundCode());
			conditionDTO.setLoanId(detailDTO.getLoanId());
			conditionDTO.setOrderNumber(detailDTO.getRtnOrderNo());
			conditionDTO.setReqNo(detailDTO.getTransctionSeq());
			MarvelsLogUtil.getInstance()
					.info(">>>>>>>>loanId" + loanId + "代扣结果查询请求参数:" + JSONObject.fromObject(conditionDTO));
			try {
				paymentResponse = withholdPaymentApi.withholdPaymentQuery(conditionDTO);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>>>>loanId" + loanId + "代扣结果查询异常:", e);
			}

			MarvelsLogUtil.getInstance().info(">>>>>>>>代扣结果查询返回参数:" + JSONObject.fromObject(paymentResponse));
			String status = "";// ；1交易中; 2代扣成功 9代扣失败
			String rtnOrderNo = "";// 第三方返回订单号
			String rtnResponseCode = "";// 扣款返回码
			String rtnResponseMsg = "";// 扣款返回信息
			String resChannel = null;
			if (null == paymentResponse) {
				status = "1";
				rtnResponseMsg = "返回信息为空";
			} else {
				resChannel = paymentResponse.getChannel();
				rtnResponseMsg = paymentResponse.getMsg();
				rtnOrderNo = paymentResponse.getOrderNumber();
				rtnResponseCode = paymentResponse.getCode();
				if ("0".equals(paymentResponse.getCode())) {// 成功
					status = "2";
				} else if ("-1".equals(paymentResponse.getCode())) {
					status = "9";
				} else {// 其余做处理中处理
					status = "1";
				}
			}
			McfePaymentWithholdDTO withholdDTO = withholdDao.selectByWithholdCode(detailDTO.getWithholdCode());
			if (null == withholdDTO) {
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>loanId:" + loanId + "查询代扣流水无记录");
				McfePaymentWithholdDetailDTO detailDTOUpdate = new McfePaymentWithholdDetailDTO();
				detailDTOUpdate.setId(detailDTO.getId());
				detailDTOUpdate.setUpdatedBy("SYSTEM");
				detailDTOUpdate.setUpdatedDate(new Date());
				detailDTOUpdate.setBatchStatus("2");// 将批次状态改成处理完成
				detailDao.updateByPrimaryKeySelective(detailDTOUpdate);
				continue;
			}

			// 更新代扣流水
			McfePaymentWithholdDetailDTO detailDTOUpdate = new McfePaymentWithholdDetailDTO();
			detailDTOUpdate.setId(detailDTO.getId());
			detailDTOUpdate.setUpdatedBy("SYSTEM");
			detailDTOUpdate.setUpdatedDate(new Date());
			detailDTOUpdate.setStatus(status);// 1交易中; 2代扣成功 9代扣失败
			detailDTOUpdate.setRtnOrderNo(rtnOrderNo);
			// 001 快付通（云科贷） ,002 宝付（云科贷） 003 宝付（口袋） 004 宝付（渤海） 005 支付宝 006 运营
			detailDTOUpdate.setResChannel(resChannel);
			detailDTOUpdate.setRtnResponseDate(new Date());
			detailDTOUpdate.setBatchStatus("2");// 将批次状态改成处理完成
			detailDTOUpdate.setRtnResponseCode(rtnResponseCode);// 扣款返回码
			detailDTOUpdate.setRtnResponseMsg(rtnResponseMsg);// 扣款返回信息
			if ("2".equals(status)) {// 成功
				detailDTOUpdate.setAmountAct(detailDTO.getAmount());
			}
			detailDao.updateByPrimaryKeySelective(detailDTOUpdate);
			if ("2".equals(status)) {// 成功
				detailDTOUpdate.setTransctionSeq(detailDTO.getTransctionSeq());
			
				try {
					withholdDTO.setRepayStyle(withholdDTO.getPayType()+"");
					withholdDTO.setFlowPayType("1");
					withholdPaymentApi.withholdSuccess(contractDTO,withholdDTO,detailDTOUpdate);
				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error(">>>>>>代扣成功处理异常:",e);
				}
			}
			// 更新代扣总记录
			McfePaymentWithholdDTO withholdDTOUpdate = new McfePaymentWithholdDTO();
			withholdDTOUpdate.setId(withholdDTO.getId());
			BigDecimal successAmount = new BigDecimal("0");
			if ("2".equals(status)) {// 成功
				successAmount = detailDTO.getAmount();
			}
			//查询代扣详情表中的处理中的数据
			int countFail=detailDao.countDealingByWithholdCode(detailDTO.getWithholdCode());
			BigDecimal amountAct = (withholdDTO.getAmountAct()==null?BigDecimal.ZERO:withholdDTO.getAmountAct()).add(successAmount);
			if (withholdDTO.getAmount().doubleValue() <= amountAct.doubleValue()) {
				withholdDTOUpdate.setStatus("1");// 代扣成功
			} else if(countFail>0){
				withholdDTOUpdate.setStatus("2");// 代扣中
			}else{
				withholdDTOUpdate.setStatus("9");// 代扣失败
			}
			withholdDTOUpdate.setUpdatedBy("SYSTEM");
			withholdDTOUpdate.setUpdatedDate(new Date());
			withholdDTOUpdate.setAmountAct(amountAct);
			withholdDao.updateByPrimaryKeySelective(withholdDTOUpdate);
		}
		return;
	}
	
}
